package com.fiap.activities;

import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.fiap.event.GPSEvent;
import com.fiap.model.Estatistica;
import com.fiap.service.Corrida;
import com.fiap.service.GPSService;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

public class MainActivity extends FragmentActivity  {
  // ===========================================================
  // Definition of the INTENT variables
  // ===========================================================
  public static final String EXTRA_POSICAO_USUARIO =
		  "com.fiap.EXTRA_POSICAO_USUARIO";

  public static final String ACAO_EXIBIR_SAUDACAO =
		  "helloandroid.ACAO_EXIBIR_SAUDACAO";
  
  public static final String CATEGORIA_SAUDACAO =
		  "helloandroid.CATEGORIA_SAUDACAO";
  
  //===========================================================
  // Singleton classes
  // ===========================================================
  static LatLng gpsUserPosition; 
  private GoogleMap map;
  private Corrida corrida;
  private Estatistica estatistica;
  private GPSService gpsService;
  
//===========================================================
  // Definition of the class variables
  // ===========================================================
  private Marker actualMarker;
  private TextView txtSpeed;
  private TextView txtDistance;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    gpsService = GPSService.getInstance();
    corrida = Corrida.getInstance();
  
    map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
			                                 .getMap();
    
    map.setMyLocationEnabled(true);
    map.getUiSettings().setMyLocationButtonEnabled(true);
    map.getUiSettings().setCompassEnabled(true);
    
    txtSpeed = (TextView) findViewById(R.id.txtSpeed);
    txtDistance = (TextView) findViewById(R.id.txtDistance);
    
    try{
    	MapsInitializer.initialize(getApplicationContext());
    	Intent intent = getIntent();
    	if (intent.hasExtra(EXTRA_POSICAO_USUARIO)) {
    		if (corrida.isRunning()){
    			String[] arrayIntentPosition = intent.getStringExtra(EXTRA_POSICAO_USUARIO)
    					                     .split(";");
    			
    			String latitude = arrayIntentPosition[0];
    			String longitude = arrayIntentPosition[1];
    			gpsUserPosition = new LatLng(Double.parseDouble(latitude), 
    					 					 Double.parseDouble(longitude));

    			corrida.addPosition(gpsUserPosition);
    			
    			actualMarker = map.addMarker(new MarkerOptions().position(gpsUserPosition)
    															.title("Jo�o")
    															.snippet("Runners porra!")
    															.icon(BitmapDescriptorFactory.fromResource(R.drawable.personagem_mapa_001)));
    			
    			map.moveCamera(CameraUpdateFactory.newLatLngZoom(gpsUserPosition, 15));
    			
    			gpsService.setEvent(new GPSEvent() 
    		    {
    		    	public void onGPSUpdate(Location location) {
    					if (!(actualMarker == null)){
    						actualMarker.remove();
    						gpsUserPosition = new LatLng(gpsService.getLastLocation().getLatitude(), 
    												     gpsService.getLastLocation().getLongitude());
    						
    						
    						estatistica = Estatistica.getInstance(gpsService.getLastLocation().getLatitude(), 
    								  gpsService.getLastLocation().getLongitude());
    						
    						estatistica.update(location.getLatitude(), location.getLongitude(), location.getSpeed());
    						
    						txtSpeed.setText(String.valueOf(location.getSpeed()));
    						
    						txtDistance.setText(String.valueOf(estatistica.getDistanciaTotal()));
    						
    						corrida.addPosition(gpsUserPosition);
    						
    						actualMarker = map.addMarker(new MarkerOptions()
    										  .position(gpsUserPosition)
    										  .title("Jo�o")
    										  .snippet("Hello World!")
    										  .icon(BitmapDescriptorFactory.fromResource(R.drawable.personagem_mapa_001)));
    						
//    						map.moveCamera(CameraUpdateFactory.newLatLngZoom(gpsUserPosition, 15));
    						
    						PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);
    						for(int i = 0 ; i < corrida.getArrayPositionsRoute().size() ; i++) {          
    							rectLine.add(corrida.getArrayPositionsRoute().get(i));
    						}
    						
    						map.addPolyline(rectLine);
    					}
    					
    		    	}		
    		    });
    		}
    	} 
    } catch (GooglePlayServicesNotAvailableException ex){
//    	User doesn't have Google Play Services Installed. Look for the latest version for Download and install it.
    	Toast toast = Toast.makeText(this, 
				 "Problemas durante o carregamento do mapa",				
				 Toast.LENGTH_SHORT);
		toast.show();
		backToInfo(null);
    }
	
    gpsService.onActivityCreated(this);
    corrida.onActivityCreated();
  }
  
  @Override
  protected void onStart() {
	super.onStart();
	gpsService.onActivityStarted();
	corrida.onActivityStarted();
  }
  
  @Override
  protected void onResume() {
		super.onResume();
		gpsService.onActivityResumed();
		corrida.onActivityResumed();
  }
  
  @Override
  protected void onPause() {
		super.onPause();
		gpsService.onActivityPaused();
		corrida.onActivityPaused();
  }
  
  @Override
  protected void onStop() {
		super.onStop();
		gpsService.onActivityStopped();
		corrida.onActivityStopped();
  }
  
  @Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		gpsService.onActivityDestroy();
		corrida.onActivityDestroy();
	}
  
  public void backToInfo (View v) {
  	Intent i = new Intent(getApplicationContext(), GPSActivity.class);
  	startActivity(i);
  }
 
} 